<?php

class Standings {
	
	public $id;
	public $liga;
	
	public $tabela;
	
	// constructor
	
	public function __construct($l = 0, $i = 0) {
		$this->id = $i;
		$this->liga = $l;
	}
	
	// functions
	
	public function getTeams() {
		$q = "SELECT tim FROM ucestvuje WHERE liga = " . $this->liga;
		$r = mysql_query("set names 'utf8'");
		$r = mysql_query($q);
		if (!mysql_num_rows($r)) throw new Exception("Nijedan tim ne ucestvuje u ligi!");
		while ($n = mysql_fetch_array($r)) {
			$this->tabela[] = new Tim($n['tim']);
		}
	}
	
	public function getTeamsStats() {
		foreach ($this->tabela as $tim) {
			$q = "SELECT id FROM utakmica WHERE (domacin = " . $tim->id . " OR gost = " . $tim->id . ") AND odigrana = 1";
			$r = mysql_query("set names 'utf8'");
			$r = mysql_query($q);
			if (!mysql_num_rows($r));
			while ($n = mysql_fetch_array($r)) {
				$tim->stats[] = $tim->getMatchStats($n['id']);
			}
			
			if (count($tim->stats)) {
				foreach ($tim->stats as $mec) {
					$pomMec = new Match($mec->mec);
					if ($pomMec->isWinner($tim)) {
						$tim->brojPoena += 2;
						$tim->wins++;
					}
					else {
						$tim->brojPoena += 1;
						$tim->loses++;
					}
					$tim->pts += $mec->pts;	// calculating scored pts
					
					// calculating conceded pts
					if ($pomMec->domacin->id == $tim->id) {
						$helpTeam = new Tim($pomMec->gost->id);
					}
					else {
						$helpTeam = new Tim($pomMec->domacin->id);
					}
						$helpTeam->stats = $helpTeam->getMatchStats($pomMec->id);
						$tim->conceded += $helpTeam->stats->pts;
				}
			}

		}
	}
	
	public function sortTeams() {
		function cmp($a, $b)
		{
			if ($a->brojPoena == $b->brojPoena) {
				if ($a->pts - $a->conceded == $b->pts - $b->conceded) {return 0;}
				else return ($a->pts - $a->conceded < $b->pts - $b->conceded) ? 1 : -1;
			}
			return ($a->brojPoena < $b->brojPoena) ? 1 : -1;
		}
		
		usort($this->tabela, "cmp");
	}
			
} // end of class Standings


?>